//
//  YSGNurseAppointmentOrderController.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2022/3/17.
//  Copyright © 2022 QDSG. All rights reserved.
//

import UIKit
import YSGFramework
import JXSegmentedView

class YSGNurseAppointmentOrderController: BaseViewController {
    var starRatingBGView : YSGNurseAppointMentStarRatingBGView?
    
    let type: Int
    init(type: Int) {
        self.type = type
        super.init(nibName: nil, bundle: nil)
        title = type == 0 ? "上门护理" : "护理咨询"
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var page : Int = 1
    var viewModel : YSGNurseAppointmentOrderViewModel = YSGNurseAppointmentOrderViewModel()
    var models : [YSGNurseAppointmentOrderModel] = []
    var nurseModels : [YSGNurseFindPatientOrderModel] = []
    var appointmentId : String?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "护理预约"
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide).priority(.low)
            make.bottom.equalToSuperview()
        }
        tableView.mj_header?.beginRefreshing()
        
    }
    
    @objc func loadData(){
        page = 1
        self.models.removeAll()
        self.nurseModels.removeAll()
        requestData()
    }
    func requestData() -> Void{
        HUDTool.showActivity()
        if type == 1 {
            viewModel.getNurseList(page: page) {[weak self] models, errorMsg, code, dataCount in
                self?.tableView.mj_header?.endRefreshing()
                self?.tableView.mj_footer?.endRefreshing()
                if dataCount == self?.nurseModels.count {
                    self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
                
                switch code {
                case .success:
                    HUDTool.hideActivity()
                    self?.nurseModels.append(contentsOf: models ?? [])
                    self?.tableView.reloadData()
                case .failure:
                    HUDTool.showError(message: errorMsg)
                }
            }
        } else {
            viewModel.getOrderList(page: page) {[weak self] models, errorMsg, code ,noMoreData in
                HUDTool.hideActivity()
                self?.tableView.mj_header?.endRefreshing()
                self?.tableView.mj_footer?.endRefreshing()
                if noMoreData {
                    self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } 
                switch code {
                case .success:
                    HUDTool.hideActivity()
                    self?.models.append(contentsOf: models ?? [])
                    self?.tableView.reloadData()
                case .failure:
                    HUDTool.showError(message: errorMsg)
                }
            }
        }
    }
    @objc func loadMore(){
        page = page + 1
        requestData()
    }
    
    private lazy var tableView: UITableView = {
        let tableView = CLTableView(delegate: self, cells: [])
        tableView.backgroundColor = .background
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_footer = refreshFooter(action: #selector(loadMore))
        tableView.register(YSGNurseAppointmentOrderCell.nibForCell(), forCellReuseIdentifier: YSGNurseAppointmentOrderCell.reuseIdentifier())
        return tableView
    }()
}

extension YSGNurseAppointmentOrderController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        view
    }
}

extension YSGNurseAppointmentOrderController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        switch type {
        case 0: return models.count
        case 1: return nurseModels.count
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YSGNurseAppointmentOrderCell.reuseIdentifier(),
                                                 for: indexPath) as! YSGNurseAppointmentOrderCell
        
        cell.delegate = self
        if type == 0 {
            cell.config(models[indexPath.section])
        }else{
            cell.nurseConfig(nurseModels[indexPath.section])
        }
        
        cell.selectionStyle = .none;
        return cell
    }
}

extension YSGNurseAppointmentOrderController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if type == 1 {
            return 227
        }
        return CGFloat(viewModel.rowHeight(models[indexPath.section].appointmentStatus))
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if type == 0 {
            let vc = YSGNurseAppointmentOrderDetailsController()
            vc.orderId = models[indexPath.section].orderId ?? ""
            vc.appointmentId = models[indexPath.section].appointmentId ?? ""
            navigationController?.pushViewController(vc, animated: true)
        }else{
            let chatVc = ChatViewController(with: nurseModels[indexPath.section].diagnoseId ?? "")
            chatVc.status = .nurse
            chatVc.title = nurseModels[indexPath.section].nurseName ?? ""
            navigationController?.pushViewController(chatVc, animated: true)
        }
    }
}



extension YSGNurseAppointmentOrderController: YSGNurseAppointmentOrderCellDelegate,YSGNurseAppointMentStarRatingBGViewDelegate {
    
    func pay(_orderId: String ,_appointmentId : String){
        let vc = YSGNurseAppointmentOrderDetailsController()
        vc.isListPay = true
        vc.orderId = _orderId
        vc.appointmentId = _appointmentId
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func evaluate(_ appointmentId: String){
        self.appointmentId = appointmentId
        starRatingBGView = YSGNurseAppointMentStarRatingBGView(frame: UIScreen.main.bounds)
        starRatingBGView?.show()
        starRatingBGView?.delegate = self
    }
    
    func nurseCancel(_ diagnoseId:String) {
        AlertTool.showAlert(self, title: "取消订单", message: "您确定要取消订单吗？", sureTitle: "确定", cancelTitle: "再想想", type: .double, sureHandler: { _ in
            HUDTool.showActivity()
            self.viewModel.patientCancelOrder(diagnoseId) {[weak self] errorMsg, code in
                HUDTool.hideActivity()
                switch code{
                case .success:
                    HUDTool.show(message: "订单取消成功")
                    self?.tableView.mj_header?.beginRefreshing()
                case .failure:
                    HUDTool.show(message: errorMsg)
                }
            }
        })
    }
    
    func cancel(_ orderId: String ,_ model :YSGNurseAppointmentOrderModel){
        if model.isSetOut == 1{
            HUDTool.show(message: "护士已经,出发无法取消订单")
            return
        }
        
        AlertTool.showAlert(self, title: "取消订单", message: "您确定要取消订单吗？", sureTitle: "确定", cancelTitle: "再想想", type: .double, sureHandler: { _ in
            HUDTool.showActivity()
            self.viewModel.orderCancel(orderId) {[weak self] errorMsg, code in
                HUDTool.hideActivity()
                switch code{
                case .success:
                    HUDTool.show(message: "订单取消成功")
                    self?.tableView.mj_header?.beginRefreshing()
                case .failure:
                    HUDTool.show(message: errorMsg)
                }
            }
        })
        
    }
    func evaluateAction(_ evaluateString : String,_ stars : String){
        
        if type == 1 {
            MyOrderViewModel.getAdvisoryOrderEvaluate(orderId: appointmentId ?? "", score: stars,comment: evaluateString, success: {[weak self] (msg) in
                HUDTool.show(message: "订单评价成功")
                self?.starRatingBGView?.dismiss()
                self?.tableView.mj_header?.beginRefreshing()
            }) { (errorMsg) in
                HUDTool.hideActivity()
                HUDTool.show(message: errorMsg)
            }
            
        } else {
            viewModel.orderComment(appointmentId ?? "", commentContent: evaluateString, commentScore: stars) {[weak self] errorMsg, code in
                switch code{
                case .success:
                    HUDTool.show(message: "订单评价成功")
                    self?.starRatingBGView?.dismiss()
                    self?.tableView.mj_header?.beginRefreshing()
                case .failure:
                    HUDTool.show(message: errorMsg)
                }
            };
        }
    }
    
}
